package com.zimin.cloud.webflux.config;

import com.zimin.cloud.webflux.handler.GlobalResponseBodyHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.accept.RequestedContentTypeResolver;

import java.util.Collections;

/**
 * @author zimin
 * @since 2021/12/24 5:28 下午
 */
@Configuration
public class WebFluxConfig {

    /**
     * <p>webflux全局统一返回</p>
     *
     * @param serverCodecConfigurer
     * @param requestedContentTypeResolver
     * @return com.zimin.cloud.webflux.handler.GlobalResponseBodyHandler
     * @since 2021-12-24 17:29:38
     */
    @Bean
    public GlobalResponseBodyHandler responseBodyHandler(ServerCodecConfigurer serverCodecConfigurer,
                                                         RequestedContentTypeResolver requestedContentTypeResolver) {
        return new GlobalResponseBodyHandler(serverCodecConfigurer.getWriters(), requestedContentTypeResolver);
    }

    /**
     * <p>处理接口跨域</p>
     *
     * @param
     * @return org.springframework.web.cors.reactive.CorsWebFilter
     * @since 2021-12-24 17:38:46
     */
    @Bean
    @Order(0)
    public CorsWebFilter corsWebFilter() {
        // 创建 UrlBasedCorsConfigurationSource 配置源，类似 CorsRegistry 注册表
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 创建 CorsConfiguration 配置，相当于 CorsRegistration 注册信息
        CorsConfiguration config = new CorsConfiguration();
        // 允许所有请求来源
        config.setAllowedOrigins(Collections.singletonList("*"));
        // 允许发送 Cookie
        config.setAllowCredentials(true);
        // 允许所有请求 Method
        config.addAllowedMethod("*");
        // 允许所有请求 Header
        config.setAllowedHeaders(Collections.singletonList("*"));
        // config.setExposedHeaders(Collections.singletonList("*")); // 允许所有响应 Header
        // 有效期 1800 秒，2 小时
        config.setMaxAge(1800L);
        source.registerCorsConfiguration("/**", config);
        // 创建 CorsWebFilter 对象
        // 创建 CorsFilter 过滤器
         return new CorsWebFilter(source);
    }

}
